package com.ruoyi.cms.websocket;

import com.alibaba.fastjson.JSONObject;
import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;

@ServerEndpoint("/chat/{room}/{username}")
@Component
public class ChatChanel {

    private static Map<String,List<Session>> userMap = new ConcurrentHashMap<>();


    @OnOpen
    public void onOpen(Session session, @PathParam("room") String room, @PathParam("username") String username) throws IOException {
        List<Session> userList = userMap.get(room);
        if(userList == null){
            userList = new Vector<>();
            userMap.put(room,userList);
        }
        userList.add(session);

        System.out.println("open..."+username+"进入直播间....当前在线用户："+userList.size());

        Map<String, Object> userProperties = session.getUserProperties();
        userProperties.put("username", username);
        userProperties.put("room", room);

        session.getBasicRemote().sendText("当前直播间在线人数为："+userList.size()+"人");

    }

    @OnMessage
    public void onMessage(String message, Session session) throws IOException {
        System.out.println("message......."+message);

        String username = (String) session.getUserProperties().get("username");
        String room = (String) session.getUserProperties().get("room");

        Map map = JSONObject.parseObject(message, Map.class);
        Integer type = (Integer) map.get("type");
        String username1 = (String) map.get("username");
        String content = (String) map.get("content");
        if(type == 1){
            List<Session> sessions = userMap.get(room);
            for (Session user : sessions) {
                user.getBasicRemote().sendText(username+":"+content);
            }
        }else{
            List<Session> sessions = userMap.get(room);
            for (Session user : sessions) {
                String targetName = (String) user.getUserProperties().get("username");
                if(targetName.equals(username1)){
                    user.getBasicRemote().sendText("[私]"+username+":"+content);
                }
            }
            session.getBasicRemote().sendText("[私]"+username+":"+content);
        }

    }

    @OnClose
    public void onClose(Session session){
        String room = (String) session.getUserProperties().get("room");
        List<Session> sessions = userMap.get(room);
        sessions.remove(session);
        System.out.println("close.......当前在线用户："+sessions.size());
    }

    @OnError
    public void onError(Throwable throwable, Session session){
        System.out.println("error.......");
    }


}
